from django.shortcuts import render, redirect
from app.models import table
# 导入分页器对象
from django.core.paginator import Paginator
from app.views import myLog_decrator
# Create your views here.


# 查询餐桌信息
def queryAll(request):
    tablelist = table.objects.all()
    # 建立分页器
    paginaor = Paginator(tablelist,3)
    # 获取当前指定页
    page = request.GET.get('page')
    # 获取当前指定页（包含有分页信息和内容的page对象）
    tablelist = paginaor.get_page(page)
    return render(request, 'showtable.html', {'tablelist': tablelist})


# 添加餐桌信息
def addtable(request):
    if request.POST:
        # 接收请求数据
        state = request.POST.get('state')
        number = request.POST.get('number')
        # 通过对象写入
        table.objects.create(state=state, number=number)
        # 写入日志
        myLog_decrator(request, "添加新餐桌可容纳人数{0}".format(number))
        return redirect('/showtable/')
        pass
    else:
        return render(request, 'addtable.html')


# 删除餐桌
def deltableById(request, id):
    table.objects.get(id=id).delete()
    # 写入日志
    myLog_decrator(request, "删除餐桌ID{0}".format(id))
    return redirect('/showtable/')


# 修改餐桌
def updateTable(request, id):
    if request.POST:
        state = request.POST.get('state')
        number = request.POST.get('number')
        # 修改数据
        table.objects.filter(id=id).update(state=state, number=number)
        # 写入日志
        myLog_decrator(request, "修改餐桌ID{0}".format(id))
        return redirect('/showtable/')
    else:
        # 根据餐桌编号查询对象获取信息
        try:
            thetable = table.objects.get(id=id)
            return render(request, 'updatetable.html', {'table': thetable})
        except:
            return redirect('/showtable/')
